package ye.guo.huang.receive.controller;

import cn.hutool.log.Log;
import cn.hutool.log.level.Level;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ye.guo.huang.datatransferdemo.model.RequestData;
import ye.guo.huang.datatransferdemo.model.ResponseResult;
import ye.guo.huang.receive.aop.Permission;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Slf4j
public class HeartBeatController {

    @GetMapping("test01")
    public Object test01(){

        return "test01";
    }

    /**
     * 接收心跳
     *  报文示例 {
     *     "appid":"52226dac949c41ada5552ce3b2b69840",
     *     "sign":"d611c6f57691fd78c28aa66c19c02601",
     *     "timestamp":111111,
     *     "data":"Oik1AAjN43nCoitAKC88cSEw6T1/Vjj1VOm3gH3qHxiAoKhbXmP/JNStqsJpnNpC0kVTd9ofIfMLKKv08/308aG8jgZiMO+czv10egTvMVk="
     *      }
     * @param data
     * @return
     */
    @Permission
    @PostMapping({"/heartBeat"})
    public ResponseResult heartBeat(@RequestBody RequestData data) {

        Log.get().log(Level.INFO,"heartBeat data={}",data);
        JSONObject param;
        try {
            param = JSONObject.parseObject(data.getParam());
        } catch (Exception var8) {
            return ResponseResult.fail(5006, "数据转换异常");
        }
        String startUpTime = String.valueOf(param.get("startUpTime") == null ? "" : param.get("startUpTime"));
        String currentTime = String.valueOf(param.get("currentTime") == null ? "" : param.get("currentTime"));

        Long lastOnLineTime = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date newTime = format.parse(currentTime);
            lastOnLineTime = newTime.getTime()  + 600000L;
        } catch (ParseException var7) {
            return ResponseResult.fail(5006, "数据转换异常");
        }
        String appid = data.getAppid();
        //todo 存心跳业务  建议用分布式锁
//        synchronized (appid){
//            ApplicationOnlineTime po = applicationOnlineTimeService.getById(appid);
//            if (po == null) {
//                po = new ApplicationOnlineTime();
//                po.setType(3);
//                po.setConsumingTime("600");
//                po.setId(appid);
//                po.setStartUpTime(startUpTime);
//                po.setLastOnlineTime(lastOnLineTime);
//            }else{
//                po.setStartUpTime(startUpTime);
//                po.setLastOnlineTime(lastOnLineTime);
//            }
//            applicationOnlineTimeService.saveOrUpdate(po);
//        }
        Log.get().log(Level.INFO,"heartBeat 执行end={}",this.getClass().getName());
        return ResponseResult.ok(1);
    }

}
